package org.example;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.example.DBConnection;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username != null && password != null) {
            try (Connection conn = DBConnection.getConnection()) {
                String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, username);
                pstmt.setString(2, password);
                ResultSet rs = pstmt.executeQuery();

                if (rs.next()) {
                    // 登录成功，重定向到 welcome.jsp
                    response.sendRedirect("welcome.jsp?username=" + username);
                } else {
                    // 登录失败，设置错误消息并重定向回登录页面
                    request.setAttribute("errorMessage", "用户名或密码错误。");
                    request.getRequestDispatcher("login.jsp").forward(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("errorMessage", "登录失败：" + e.getMessage());
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } else {
            // 如果用户名或密码为空，重定向回登录页面
            request.setAttribute("errorMessage", "用户名和密码不能为空。");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}